package com.glodon.paas.util;

import java.io.Closeable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;



public class ObjectUtil {
    /**
     * 将对象转换成json，此方法不做任何异常处理，可用以日志打印
     * 
     * @param obj
     * @return
     */
    public static String toJson(Object obj){
        try {
            return JSON.toJSONString(obj);
        } catch (Exception e) {
            return "{\"error\":\"obj2json error\"}";
        }
    }
 
    /**
     * 将POJO对象转换成Map<String,String>
     * 属性名做key,属性值做value
     * @param obj
     * @return Map<String,String>
     */
    public static Map<String,String> toMap(Object pojo){
        Field[] fs = pojo.getClass().getDeclaredFields();
        Map<String, String> temp = new HashMap<String, String>();
        Object v;
        for(Field f : fs){
            try {
                f.setAccessible(true);
                v = f.get(pojo);
                if(v != null){
                    temp.put(f.getName(), v.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
                temp.put("error", "object to map error.");
            }               
        }
        
        return temp;
    }
    
    /**
     * 线程休眠millis毫秒<br>
     * eatException=true  出错不抛异常<br>
     * eatException=false 出错抛出异常RuntimeException<br>
     * @param millis
     * @param eatException 
     */
    public static void sleep(long millis, boolean eatException){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            if(eatException){
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
    
    /**
     * 关闭需要关闭的资源<br>
     * eatException=true  出错不抛异常<br>
     * eatException=false 出错抛出异常RuntimeException<br>
     * @param obj
     */
    public void close(Closeable obj, boolean eatException){
        if(obj!=null){
            try {
                obj.close();
            } catch (Exception e) {
                if(eatException){
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
    }
}
